package com.jiangnan.repository

import com.jiangnan.api.client.BookApiClient
import com.jiangnan.api.client.ISBNApiClient
import com.jiangnan.entity.Book
import com.jiangnan.entity.PageResult
import com.jiangnan.entity.Res
import okhttp3.MultipartBody
import retrofit2.Response
import java.io.File

class BookRepository {

    // 挂起函数，通过 ISBN 获取图书信息
    suspend fun fetchBook(apiKey: String, isbn: String): Res<Book> {
        return ISBNApiClient.isbnApiService.getBookByIsbn(apiKey, isbn)
    }

    /**
     * 获取所有图书
     */
    suspend fun getAllBooks(page : Int?, pageSize : Int?, requestParam : String?): Res<PageResult<Book>> {
        return BookApiClient.bookApiService.getAllBooks(page, pageSize, requestParam)
    }

    /**
     * 获取所有图书,根据借阅数量排序
     */
    suspend fun getAllBooksOrderByBorrowNum(page : Int?, pageSize : Int?, requestParam : String?): Res<PageResult<Book>> {
        return BookApiClient.bookApiService.getAllBooksOrderByBorrowNum(page, pageSize, requestParam)
    }

    suspend fun saveBook(book: Book): Res<String> {
        return BookApiClient.bookApiService.saveBook(book)
    }

    /**
     * 上传图片
     */
    suspend fun uploadImage(file: MultipartBody.Part): Response<Res<String>> {
        return BookApiClient.bookApiService.uploadImage(file)
    }

    /**
     * 借阅图书：调用后端接口，将借阅记录插入用户借书表，并更新图书剩余数量
     */
    suspend fun borrowBook(userId: Long, bookId: Int): Res<String> {
        return BookApiClient.bookApiService.borrowBook(userId, bookId)
    }

    /**
     * 根据用户ID查询其借阅的图书列表
     */
    suspend fun getBorrowedBooks(userId: Long): Res<List<Book>> {
        return BookApiClient.bookApiService.getBorrowedBooks(userId)
    }

    /**
     * 调用还书接口，将书归还后：
     *  - user_book 表中更新归还时间
     *  - book 表中剩余数量加 1
     */
    suspend fun returnBook(userId: Long, bookId: Int): Res<String> {
        return BookApiClient.bookApiService.returnBook(userId, bookId)
    }

    suspend fun borrowBookByQrcode(userId: Long, bookIsbn: String): Res<String> {
        return BookApiClient.bookApiService.borrowBookByQrcode(userId, bookIsbn)
    }

    suspend fun getAllBorrowedBooks(userId: Long): Res<List<Book>> {
        return BookApiClient.bookApiService.getAllBorrowedBooks(userId)
    }

    suspend fun getAllReturnedBooks(userId: Long): Res<List<Book>> {
        return BookApiClient.bookApiService.getAllReturnedBooks(userId)
    }

}